package com.htgd.gardenexpo.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.htgd.gardenexpo.dto.DeviceDTO;
import com.htgd.gardenexpo.dto.GoodsOrderQuery;
import com.htgd.gardenexpo.entity.CommonResult;
import com.htgd.gardenexpo.entity.GeConMealOrder;
import com.htgd.gardenexpo.entity.GeConSeatMeal;
import com.htgd.gardenexpo.entity.GeConTelescopeMeal;
import com.htgd.gardenexpo.service.DeviceService;
import com.htgd.gardenexpo.service.GeConMealOrderService;
import com.htgd.gardenexpo.utils.TokenUtil;
import com.htgd.gardenexpo.vo.DeviceNumsVO;
import com.htgd.gardenexpo.vo.QrCodeVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author: 王秀田
 * @date: 2024/11/18 17:09
 * @description: 设备管理
 */
@RequestMapping("/api/device")
@Api(tags = "设备管理")
@RestController
@Slf4j
public class DeviceController {

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private GeConMealOrderService geConMealOrderService;

    @ApiOperation("小程序在甲板登录")
    @PostMapping(value = "/token")
    public CommonResult<Map<String,Object>> wxLogin(String code,HttpServletRequest request) {
        String accessToken = request.getHeader("Access_token");
        String openId = TokenUtil.getUsernameFromToken(accessToken);
        log.info("小程序在甲板登录：{},{}",code,openId);
        try {
            //获取token
            Map<String,Object> token = deviceService.wxLogin(code,openId);
            if(token==null){
                return CommonResult.error("小程序在甲板登录失败");
            }else{
                return CommonResult.success("小程序在甲板登录成功",token);
            }
        } catch (Exception e) {
            return CommonResult.error("小程序在甲板登录失败："+e);
        }
    }

    @ApiOperation("查询设备列表")
    @GetMapping(value = "/list")
    public CommonResult<JSONArray> list(){
        try {
            return deviceService.getDeviceList();
        }catch (Exception e){
            CommonResult<JSONArray> result = new CommonResult<>();
            result.setData(null);
            result.setMessage("查询失败");
            result.setCode(500);
            return result;
        }
    }

    @GetMapping(value = "/details")
    @ApiOperation("详情")
    @Transactional
    public CommonResult<JSONObject> details(String deviceId) {
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            JSONObject jsonObject = deviceService.getDeviceDetails(deviceId);
            result.setCode(200);
            result.setMessage("查询成功");
            result.setData(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setMessage("查询失败");
        }
        return result;
    }

    @ApiOperation("生成设备二维码")
    @GetMapping(value = "/saveDeviceQrCode")
    public ResponseEntity<byte[]> saveDeviceQrCode(@RequestParam String deviceId, @RequestParam String typeId){
        return deviceService.saveDeviceQrCode(deviceId,typeId);
    }

    @ApiOperation(value = "获取设备二维码")
    @GetMapping(value = "/getQrCode", produces = MediaType.IMAGE_PNG_VALUE)
    public @ResponseBody byte[] getQrCode(@RequestParam String deviceId) {
        return deviceService.getQrCode(deviceId);
    }

    @ApiOperation(value = "获取望眼镜套餐列表")
    @GetMapping(value = "/getTelescopeMealList")
    public CommonResult<List<GeConTelescopeMeal>> getTelescopeMealList() {
        CommonResult<List<GeConTelescopeMeal>> result = new CommonResult<>();
        result.setCode(200);
        result.setMessage("查询成功");
        result.setData(deviceService.getTelescopeMealList());
        return result;
    }

    @ApiOperation(value = "获取座椅套餐列表")
    @GetMapping(value = "/getSeatMealList")
    public CommonResult<List<GeConSeatMeal>> getSeatMealList() {
        CommonResult<List<GeConSeatMeal>> result = new CommonResult<>();
        result.setCode(200);
        result.setMessage("查询成功");
        result.setData(deviceService.getSeatMealList());
        return result;
    }

    @PostMapping(value = "/deviceSubmit")
    @ApiOperation("确定兑换")
    public CommonResult<JSONObject> deviceSubmit(@RequestBody DeviceDTO device, HttpServletRequest request){
        String accessToken = request.getHeader("Access_token");
        String openId = TokenUtil.getUsernameFromToken(accessToken);
        log.info("兑换设备套餐：{}，{}",device,openId);
        try {
            return deviceService.deviceSubmit(device,openId);
        } catch (Exception e) {
            e.printStackTrace();
            CommonResult<JSONObject> result = new CommonResult<>();
            result.setCode(500);
            result.setMessage("设备离线,兑换失败");
            return result;
        }
    }

    @ApiOperation("查询设备订单列表")
    @GetMapping(value = "/deviceList")
    public CommonResult<List<GeConMealOrder>> deviceList(GoodsOrderQuery goodsOrderQuery, HttpServletRequest request){
        log.info("后台订单列表：{},{}",goodsOrderQuery,request);
        CommonResult<List<GeConMealOrder>> result = new CommonResult<>();
        try {
            PageInfo<GeConMealOrder> list = geConMealOrderService.pageList(goodsOrderQuery, request);
            result.setCode(200);
            result.setMessage(String.valueOf(list.getTotal()));
            result.setData(list.getList());
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setMessage("查询失败");
        }
        return result;
    }

    @ApiOperation("读取望远镜剩余时长")
    @GetMapping(value = "/getTelescopeRemainingTime")
    public CommonResult getTelescopeRemainingTime(String num){
        log.info("读取望远镜剩余时长：{}",num);
        return deviceService.getTelescopeRemainingTime(num);
    }

    @ApiOperation("读取座椅剩余时长")
    @GetMapping(value = "/getSeatRemainingTime")
    public CommonResult getSeatRemainingTime(String num){
        log.info("读取座椅剩余时长：{}",num);
        return deviceService.getSeatRemainingTime(num);
    }

    @ApiOperation("设备订单回调")
    @PostMapping(value = "/orderCallback")
    public CommonResult<JSONObject> orderCallback(@RequestBody String id){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            GeConMealOrder geConMealOrder = new GeConMealOrder();
            geConMealOrder.setId(id);
            geConMealOrder.setStatus("1");
            geConMealOrderService.updateById(geConMealOrder);
            result.setCode(200);
            result.setMessage("回调成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setMessage("回调失败失败");
        }
        return result;
    }

    @ApiOperation("获取各设备使用人次")
    @GetMapping(value = "/getUseNums")
    public CommonResult getUseNums(@RequestParam(required = false) String startTime,
                                                 @RequestParam(required = false) String endTime,
                                                 @RequestParam(required = false) String deviceType,
                                                 @RequestParam(required = false) String deviceCode){
       log.info("综管-获取各设备使用人次：{},{},{},{}",startTime,endTime,deviceType,deviceCode);
       return deviceService.getUseNums(startTime,endTime,deviceType,deviceCode);
    }

    @ApiOperation("关闭设备")
    @DeleteMapping(value = "/closeDevice")
    public CommonResult closeDevice(@RequestParam String deviceId,
                                    @RequestParam String type){
        log.info("甲板-关闭设备：{},{}",deviceId,type);
        return deviceService.closeDevice(deviceId,type);
    }

}
